import 'dart:math';

import 'package:extended_tabs/extended_tabs.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:get/get.dart';
import 'package:laos_mall/common/base/page_size_controller.dart';
import 'package:laos_mall/common/config/app_const.dart';
import 'package:laos_mall/common/style/app_style.dart';
import 'package:laos_mall/common/style/extension_util.dart';
import 'package:laos_mall/common/widght/image_widget.dart';
import 'package:laos_mall/common/widght/item_widget.dart';
import 'package:laos_mall/common/widght/list_title_widget.dart';
import 'package:laos_mall/common/widght/mall/zb_Item_widget.dart';
import 'package:laos_mall/common/widght/toast/showtoast.dart';
import 'package:laos_mall/models/category/para_product.dart';
import 'package:laos_mall/pages/main/config.dart';
import 'package:laos_mall/pages/main/shopping_cart/faviurites/view.dart';
import 'package:laos_mall/pages/main/widgets/number_mall_widget.dart';
import 'package:laos_mall/pages/main/widgets/product_item.dart';
import 'package:laos_mall/user_data.dart';

import '../../../app_route.dart';
import 'logic.dart';

class ShoppingCartPage extends StatelessWidget {
  ShoppingCartPage({Key? key}) : super(key: key);

  late ShoppingCartLogic logic;
  // final ShoppingCartLogic logic = Get.put(ShoppingCartLogic());
  @override
  Widget build(BuildContext context) {
    logic = Get.find<ShoppingCartLogic>();
    return GetBuilder<ShoppingCartLogic>(builder: (logic) {

      return Obx(() {
        return Scaffold(
        appBar: AppBar(
          titleSpacing: 0,
          title: Row(
            children: [
              TabBar(
                isScrollable: false,
                tabs: [
                  // Tab(text: "Woman",child: Text("Woman",textAlign: TextAlign.center,style: AppStyle.textStyle,).addContainer(width: 55,color: Colors.transparent),),
                  Tab(text: "shopping_bag".trParams({"id": logic.cartModel?.total?.total_count == 0 || logic.cartModel?.total?.total_count == null ? "" :"[${logic.cartModel?.total?.total_count}]"})),
                  Tab(text: "favourites".tr)
                ],
                // indicatorPadding: EdgeInsets.only(bottom: 5.h, left: 8, right: 8),
                indicatorSize: TabBarIndicatorSize.label,
                controller: logic.tabController,
                indicatorColor: Colors.transparent,
                padding: EdgeInsets.zero,
                labelPadding: EdgeInsets.zero,
              )
                  .addContainer(height: 32.h, color: Colors.transparent)
                  .addExpand(),
              Text(logic.isManager.value == true ? "cancel".tr : "manage".tr,
                textAlign: TextAlign.right,
                style: AppStyle.textStyle,)
                  .addContainer(color: Colors.transparent, width: 100.w,
                  alignment: Alignment.centerRight,
                  padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10))
                  .addGestureTap(() {
                logic.isManager.value = !logic.isManager.value;

              })
              // AppButton.textSizeBtn(() {}, "manage".tr,
              //     style: AppButtonStyle.textBtn,width: 70.w,bgColor: Colors.red,alignment: Alignment.centerRight)
            ],
          ),
        ),
        body: Column(children: <Widget>[

          Expanded(child: ExtendedTabBarView(
            shouldIgnorePointerWhenScrolling: false,
            controller: logic.tabController,
            children: [
              Column(children: [
                _buildCart(),
                _buildProdut()
              ],).addSingleChildScrollView(),
              FaviuritesPage()
            ],
          ))
        ]),
        bottomNavigationBar: _buildBottom()
        );
      });
    });
  }

  Widget? _buildBottom(){
    if(!logic.showBottomBox.value){
      return null;
    }
   return logic.isManager.value
        ? _buildDeleteBox()
        : _buildContinueBox();
  }

  _buildCart() {

    return PageSizeView(itemBuilder: (context, index,data) {
      return _buildCartItem(index);
    },
      itemCount: logic.dataSource.length,
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(), controller: logic,
      emptyView: Column(children: [
        Image.asset("img_handbag".toImgPath(),width: 46.w,height: 46.w,),
        SizedBox(height: 18.h,),
        Text("empty_cart".tr,textAlign: TextAlign.center,style: AppStyle.subtitleLightStyleGray,)
      ],).addPadding(EdgeInsets.symmetric(vertical: 35.h)),
    );
  }

  _buildCartItem(index) {
    var item = logic.dataSource[index];
    bool isSel = item.is_checked ?? false;
    return Slidable(
      closeOnScroll: false,
      endActionPane: ActionPane(motion: ScrollMotion(), children: [
        SlidableAction(
          onPressed: (_) {
            logic.deleteProduct(index);
          },
          backgroundColor: Color(0xFFFE4A49),
          foregroundColor: Colors.white,
          label: 'delete'.tr,
          padding: EdgeInsets.symmetric(vertical: 12),
        )
      ]),
      child: ItemWidget(prefixItem: (isSel
          ? Icon(
        Icons.check_circle,
        size: 16.h,
      )
          : Icon(
        Icons.radio_button_unchecked,
        size: 16.h,
      )).addPadding(EdgeInsets.symmetric(horizontal: 10.w)).addGestureTap(() {
        logic.clickSelectIcon(index);
      }), suffixItem:
      ListTitleWidget(
        maxLeadingW: 120.w,
        leading: ImageWidget(url:item.pic_thumb, fit: BoxFit.cover,)
            .addContainer(color: Colors.transparent, width: 120.w, height: 120.w,),
        title: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(item.product_name,maxLines: 2,overflow: TextOverflow.ellipsis,)
                .addPadding(
                EdgeInsets.only(left: 16.w)),
            Text(item.sku?.sku_value ?? "none".tr, style: AppStyle.subtitleLightStyle,).addPadding(
                EdgeInsets.only(left: 16.w, top: 9.h)),
            NumberMallWidget(number: item.quantity),
            Text("${Config.symbol}${item.original_price}",
              style: AppStyle.textStyle.copyWith(fontWeight: FontWeight.bold),)
                .addPadding(EdgeInsets.only(left: 16.w))
          ],),
        paddingOfLeft: EdgeInsets.zero,
        showArrow: false,
      ).addGestureTap(() {
        Get.toNamed(AppRouter.productDetail);
      }).addExpand(),),).addContainer(height: 120.w, margin: EdgeInsets.only(bottom: 20.h));
  }

  ///商品列表
  _buildProdut() {
    return ProductItemWidget(physics: NeverScrollableScrollPhysics(),
      title: "may_like".tr,
      topSpace: 0,para: ParamProduct(),name: "cart",autoPage: false,);
  }

  _buildContinueBox() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            ZBItemWidget(style: ZBItemStyle.checkAll,isSel: logic.isAll.value,).addContainer(
                color: Colors.transparent,
                padding: EdgeInsets.symmetric(horizontal: 10.w),
                height: double.infinity,
            ).addGestureTap(() {
              logic.clickAll();
            }),
            Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Text(
                  "total".tr,
                  style: AppStyle.subtitleLightStyle.copyWith(fontSize: 8.sp),
                ),
                SizedBox(
                  width: 3.w,
                ),
                Text(
                  "${Config.symbol}${logic.cartModel?.total?.product_amount ?? "0"}",
                  textAlign: TextAlign.end,
                  style: AppStyle.textStyle.copyWith(
                      fontWeight: FontWeight.bold),
                ),
              ],
            ).addPadding(EdgeInsets.only(top: 8.w)).addExpand()
          ],
        )
            .addContainer(
          height: 54.h,
          padding: EdgeInsets.only(right: 10.w),
          border: Border(
              top: BorderSide(color: AppColor.dividerColor, width: 0.5)),
        )
            .addExpand(),
        AppButton.fullBtn(
            logic.clickContinue, "continue".trParams({"id": logic.getNumberSel() == 0 ? "" : "(${logic.getNumberSel()})"}),
            bgColor: "#333333".toColor,
            style: AppButtonStyle.normal,
            padding: EdgeInsets.zero,
            size: Size(170.w, 54.h)),
      ],
    ).addContainer(color: AppColor.primaryColor, height: 54.h);
  }

  _buildDeleteBox() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        ZBItemWidget(style: ZBItemStyle.checkAll, isSel: logic.isAll.value,)
            .addContainer(
            color: Colors.transparent,
            padding: EdgeInsets.symmetric(horizontal: 10.w),
            height: double.infinity).addGestureTap(() {
          logic.clickAll();
        }),
        Spacer(),
        AppButton.sizeBtn(
            logic.cleanAll, "clear_cart".tr,
            style: AppButtonStyle.hollowBlack,
            size: Size(100.w, 32.h)),
        SizedBox(width: 20.w,),
        AppButton.sizeBtn(
            logic.cancelCheck, "clear_check".tr,
            style: AppButtonStyle.normal,
            size: Size(100.w, 32.h)),
        SizedBox(width: 20.w,)
      ],
    ).addContainer(color: AppColor.white, border: Border(
        top: BorderSide(color: AppColor.dividerColor, width: 0.5)),
        height: 54.h
    );
  }

}
